package middleware

import (
	"github.com/gin-gonic/gin"
	"go-programming-tour-book/blog-service/global"
	"go-programming-tour-book/blog-service/pkg/Email"
	"go-programming-tour-book/blog-service/pkg/app"
	"go-programming-tour-book/blog-service/pkg/errcode"
)

func Recovery() gin.HandlerFunc {
	defaultMailer := Email.NewEmail(&Email.SMTPInfo{
		Host:     global.EmailSetting.Host,
		Port:     global.EmailSetting.Port,
		IsSSL:    global.EmailSetting.IsSSL,
		UserName: global.EmailSetting.Username,
		Password: global.EmailSetting.Password,
		From:     global.EmailSetting.From,
	})

	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				s := "panic recover err:%v"

				global.Logger.WithCallersFrames().Fatalf(s, err)

				err := defaultMailer.SendMail(global.EmailSetting.To, "报警了", "hello world！！！")

				if err != nil {
					global.Logger.Fatalf("mail fail:$v", err)
				}

				app.NewResponse(c).ToErrorResponse(errcode.ServerError)

				c.Abort()
			}
		}()

		c.Next()
	}
}
